package com.wnhz.work.jy.wxapi;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.solidfire.gson.Gson;
import com.solidfire.gson.reflect.TypeToken;
import com.tencent.mm.sdk.modelbase.BaseReq;
import com.tencent.mm.sdk.modelbase.BaseResp;
import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.wnhz.work.jy.MyApplication;
import com.wnhz.work.jy.MyMain;
import com.wnhz.work.jy.activity.BindinPhoneNumber;
import com.wnhz.work.jy.bean.UserBean;
import com.wnhz.work.jy.bean.WeiXinBean1;
import com.wnhz.work.jy.bean.WeiXinMessageBean;
import com.wnhz.work.jy.utils.ConfigUtil;
import com.wnhz.work.jy.utils.xutils3.MyCallBack;
import com.wnhz.work.jy.utils.xutils3.XUtil;
import com.wnhz.work.jy.view.ShowPopupWindow;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * Created by ntop on 15/9/4.
 */
public class WXEntryActivity extends Activity implements IWXAPIEventHandler {
    private static final String TAG = "WXEntryActivity";
    private static final String SECRET = "fcc43444718db46ce38abe82b65de36a";
    private static final String WXAPP_ID = "wx054406f5ccd828da";
    private String url_access_token = "https://api.weixin.qq.com/sns/oauth2/access_token?";
    private String url_refresh_token = "https://api.weixin.qq.com/sns/oauth2/refresh_token?";
    private String userinfo_url = "https://api.weixin.qq.com/sns/userinfo?";
    private Map<String, Object> map = new HashMap<>();
    private Map<String, Object> map_user = new HashMap<>();
    private Map<String, Object> map_refresh_token = new HashMap<>();
    private Gson gson;

    public interface LogInFinish {
        void fin(int i);
    }

    // IWXAPI 是第三方app和微信通信的openapi接口
    private IWXAPI api;
    private WeiXinMessageBean bean;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 通过WXAPIFactory工厂，获取IWXAPI的实例
        api = WXAPIFactory.createWXAPI(this, WXAPP_ID, false);
        api.registerApp(WXAPP_ID);

        api.handleIntent(getIntent(), this);
        gson = new Gson();
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

        setIntent(intent);
        api.handleIntent(intent, this);
    }

    // 微信发送请求到第三方应用时，会回调到该方法
    @Override
    public void onReq(BaseReq req) {

    }

    // 第三方应用发送到微信的请求处理后的响应结果，会回调到该方法
    @Override
    public void onResp(BaseResp resp) {
        int result = 0;


        switch (resp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                Log.e("resp", resp.getType() + "55");
                if (resp.getType() == 1) {

                    MyApplication.getInstance().is_start_login = true;
                    String code = ((SendAuth.Resp) resp).code;
                    System.out.println(code);
                    map.put("appid", WXAPP_ID);
                    map.put("secret", SECRET);
                    map.put("code", code);
                    map.put("grant_type", "authorization_code");
                    XUtil.Post(url_access_token,map,new MyCallBack<String>(){
                        @Override
                        public void onSuccess(String result) {
                            super.onSuccess(result);
                            java.lang.reflect.Type type = new TypeToken<WeiXinBean1>() {
                            }.getType();

                            try {
                                JSONObject jsonObject = new JSONObject(result);
                                WeiXinBean1 bean1 = new WeiXinBean1();
                                bean1.setAccess_token(jsonObject.optString("access_token"));
                                bean1.setExpires_in(jsonObject.optString("expires_in"));
                                bean1.setRefresh_token(jsonObject.optString("refresh_token"));
                                bean1.setOpenid(jsonObject.optString("openid"));
                                bean1.setScope(jsonObject.optString("scope"));
                                bean1.setUnionid(jsonObject.optString("unionid"));
                                MyApplication.getInstance().bean1 = bean1;
                                Log.d(TAG, "onSuccess: "+bean1.toString());
                                getWeiXinUser();
                            } catch (JSONException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void onFinished() {
                            super.onFinished();
                        }
                    });

                } else if (resp.getType() == 255) {
                    System.out.println(255 + "");
                    finish();
                }else {
                    System.out.println("platform "+resp.getType());
                }


                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                finish();
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                break;
            default:
                break;
        }

		/*if (WXEntryActivity.this != null) {

			
		}*/
        finish();
    }


    private void getWeiXinUser() {
        map_user.put("access_token", MyApplication.getInstance().bean1.getAccess_token());
        map_user.put("openid", MyApplication.getInstance().bean1.getOpenid());
        XUtil.Post(userinfo_url, map_user, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                System.out.println("result" + result);
                bean = new WeiXinMessageBean();
                bean = gson.fromJson(result.toString(), WeiXinMessageBean.class);

				/*bean.setOpenid(jsonObject.optString("openid"));
				bean.setNickname(jsonObject.optString("nickname"));
				bean.setSex(jsonObject.optString("sex"));
				bean.setLanguage(jsonObject.optString("language"));
				bean.setCity(jsonObject.optString("city"));
				bean.setProvince(jsonObject.optString("province"));
				bean.setCountry(jsonObject.optString("country"));
				bean.setHeadimgurl(jsonObject.optString("headimgurl"));
				bean.setUnionid(jsonObject.optString("unionid"));*/
                Log.e(TAG, "onSuccess: "+bean.toString());
                MyApplication.getInstance().bean = bean;
                if (MyApplication.getInstance().sign_map == null){
                    login();
                }else {
                    sign();
                }


                Log.e(TAG, "onSuccess: "+bean.toString() );
                //thirdPartyLogIn(bean.getOpenid(), 3);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                Log.e(TAG, "onError:ex "+ex);
            }

            @Override
            public void onFinished() {
                super.onFinished();
            }
        });


    }
    public Dialog dialog;
    public void showDialog() {

        if (null == dialog) {
            dialog = ShowPopupWindow.unCancleableDialog(this);
        }
        dialog.show();
    }

    public void closeDialog() {
        if (null != dialog) {
            dialog.dismiss();
        }
    }
    private void sign() {
        Map<String, Object> map = MyApplication.getInstance().sign_map;
        map.put("userName", MyApplication.getInstance().bean.getNickname());
        map.put("userImg", MyApplication.getInstance().bean.getHeadimgurl());
        map.put("openId", MyApplication.getInstance().bean.getOpenid());
        map.put("unionId", MyApplication.getInstance().bean.getUnionid());
        //showDialog();

        XUtil.Post(ConfigUtil.REGISTER_NORMAL, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String re = jsonObject.optString("result");
                    MyApplication.getInstance().sign_map = null;
                    if ("1".equals(re)){
                        MyApplication.getInstance().is_start_login = false;
                    }
                    String info = jsonObject.optString("info");
                    Toast.makeText(getApplication(),info,Toast.LENGTH_SHORT).show();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();

            }
        });

    }

    private void login() {
        Map<String,Object> map = new HashMap<>();
        map.put("openId",MyApplication.getInstance().bean1.getOpenid());
        map.put("unionId",MyApplication.getInstance().bean1.getUnionid());
        XUtil.Post(ConfigUtil.LOGIN,map,new MyCallBack<String>(){
            @Override
            public void onSuccess(String result) {
                Log.e(TAG, "onSuccess: "+result );
                super.onSuccess(result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String re = jsonObject.optString("result");
                    if ("1".equals(re)){
                        MyApplication.getInstance().is_start_login = false;
                        String r = jsonObject.optString("info");
                        UserBean userBean = new UserBean();
                        userBean = new Gson().fromJson(r,UserBean.class);
                        MyApplication.getInstance().userBean = userBean;
                        Log.e(TAG, "onSuccess: "+userBean.toString() );
                        startActivity(new Intent(WXEntryActivity.this, MyMain.class));
                    }else if ("2".equals(re)){
                        startActivity(new Intent(getApplicationContext(), BindinPhoneNumber.class));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    }


    /**
     * 刷新Access_token
     */
    private void getRefreshToken() {
        if (MyApplication.getInstance().bean1 != null) {
            map_refresh_token.put("appid", WXAPP_ID);
            map_refresh_token.put("grant_type", "refresh_token");
            map_refresh_token.put("refresh_token", MyApplication.getInstance().bean1.getRefresh_token());
            XUtil.Post(url_refresh_token,map_refresh_token,new MyCallBack<String >(){
                @Override
                public void onSuccess(String result) {
                    super.onSuccess(result);
                    Log.e(TAG, "onSuccess: toa  "+result );
                }
            });

        }

    }

    private String addUrl(Map<String, String> map, String s) {
        String url;
        StringBuffer kv = new StringBuffer();
        Set set = map.keySet();
        for (Object key : set) {
            String k = (String) key;
            String v = map.get(k);
            kv.append(k);
            kv.append("=");
            kv.append(v);
            kv.append("&");
        }
        if (kv.length() > 1) {
            kv.deleteCharAt(kv.length() - 1);
        }
        url = s + kv;

        return url;
    }

    @Override
    protected void onStop() {
        // TODO Auto-generated method stub
        super.onStop();
    }


}
